package com.yue92.datalife.service.impl;

import com.yue92.datalife.common.CommonUtil;
import com.yue92.datalife.common.RedisUtil;
import com.yue92.datalife.model.User;
import com.yue92.datalife.repository.UserRepository;
import com.yue92.datalife.service.AbstractDbService;
import com.yue92.datalife.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends AbstractDbService<User, Long> implements IUserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Optional<User> getByToken(String token) {
        String userId = redisTemplate.opsForValue().get(RedisUtil.getTokenKey(token));
        if (StringUtils.isEmpty(userId)) {
            return Optional.empty();
        }

        return userRepository.findById(Long.valueOf(userId));
    }

    @Override
    public Optional<User> getByCertificate(String email, String password) {
        return userRepository.findByEmailAndPassword(email, CommonUtil.encode(password));
    }

    @Override
    public String generateToken(Long userId) {
        String token = CommonUtil.generateToken();
        redisTemplate.opsForValue().set(RedisUtil.getTokenKey(token), userId.toString(), 2592000, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set(RedisUtil.getUidTokenKey(userId), token, 2592000, TimeUnit.SECONDS);

        return token;
    }

    @Override
    public void deleteOldToken(Long userId) {
        String oldToken = redisTemplate.opsForValue().get(RedisUtil.getUidTokenKey(userId));
        if (!StringUtils.isEmpty(oldToken)) {
            redisTemplate.delete(RedisUtil.getTokenKey(oldToken));
        }
    }

    @Override
    public JpaRepository<User, Long> getRepository() {
        return userRepository;
    }

    @Override
    protected Class<User> getModelClass() {
        return User.class;
    }
}
